<template>
  <van-popup v-model:show="showPopup" position="right" destroy-on-close :style="{ width: '100%', height: '100%' }" teleport="body">
    <van-nav-bar title="客户详情" fixed @click-right="close">
      <template #right>
        <van-icon name="cross" size="18" />
      </template>
    </van-nav-bar>
    <div class="detail-wrapper">
      <van-cell-group>
        <van-cell title="姓名" :value="form.nickName" />
        <van-cell title="手机号" :value="form.mobile" />
        <van-cell title="状态" :value="form.state === 1 ? '正常' : '禁用'" />
      </van-cell-group>
      <div class="btn-wrapper">
        <van-button class="btn-item" type="primary" size="small" block @click="editCustomer">编辑</van-button>
        <van-button class="btn-item" type="danger" size="small" block @click="deleteCustomer">删除</van-button>
      </div>
      <van-cell>
        <template #title>
          <div class="title">客户持仓</div>
        </template>
        <template #label>
          <div class="content-wrapper">
            <div class="content-item">
              <div class="content-item-value">
                <span>{{ formatAmountBySize(form.assets || 0) }}</span>
                <span class="unit">{{ formatAmountTextBySize(form.assets || 0) }}</span>
              </div>
              <div class="content-item-title">持有资产</div>
            </div>
            <van-divider vertical />
            <div class="content-item">
              <div class="content-item-value">
                <span>{{ formatAmountBySize(form.cost || 0) }}</span>
                <span class="unit">{{ formatAmountTextBySize(form.cost || 0) }}</span>
              </div>
              <div class="content-item-title">持有成本</div>
            </div>
            <van-divider vertical />
            <div class="content-item">
              <div class="content-item-value" :class="form.symbol === '' ? '' : form.symbol === '+' ? 'income' : 'loss'">
                <span>{{ form.symbol }}</span>
                <span>{{ formatAmountBySize(Math.abs(form.profitLoss || 0)) }}</span>
                <span class="unit">{{ formatAmountTextBySize(Math.abs(form.profitLoss || 0)) }}</span>
              </div>
              <div class="content-item-title">浮动盈亏</div>
            </div>
          </div>
        </template>
      </van-cell>
      <div class="btn-wrapper">
        <van-button class="btn-item" size="small" type="primary" block @click.stop="startTrade(1)">买入</van-button>
        <van-button class="btn-item" size="small" type="danger" block @click.stop="startTrade(2)">卖出</van-button>
      </div>
      <van-cell-group>
        <van-cell>
          <template #title>
            <div class="title">交易明细</div>
          </template>
        </van-cell>
        <van-cell v-for="item in transactionLogList" :key="item.id" title="">
          <template #label>
            <div class="trade-wrapper">
              <div class="trade-type">
                <van-tag v-if="item.transactionType === 1" type="primary">买入</van-tag>
                <van-tag v-else type="danger">卖出</van-tag>
              </div>
              <div class="trade-info">
                <div class="trade-info-item">
                  <div class="trade-info-label">{{ item.transactionType === 1 ? '买入' : '卖出' }}日期：</div>
                  <div class="trade-info-value">{{ dayjs(item.transactionDate).format('YYYY-MM-DD') }}</div>
                </div>
                <div class="trade-info-item">
                  <div class="trade-info-label">{{ item.transactionType === 1 ? '买入' : '卖出' }}金额：</div>
                  <div class="trade-info-value bold">{{ formatAmountBySize(Math.abs(item.transactionAmount)) }}{{ formatAmountTextBySize(Math.abs(item.transactionAmount)) }}</div>
                </div>
                <div class="trade-info-item">
                  <div class="trade-info-label">{{ item.transactionType === 1 ? '买入' : '卖出' }}份额：</div>
                  <div class="trade-info-value bold">{{ Math.abs(item.transactionUnits) }}份</div>
                </div>
              </div>
              <template v-if="item.transactionType === 2">
                <div class="content-item income-loss">
                  <div class="content-item-value" :class="item.symbol === '' ? '' : item.symbol === '+' ? 'income' : 'loss'">
                    <span>{{ item.symbol }}</span>
                    <span>{{ formatAmountBySize(Math.abs(item.profitLossAmount)) }}</span>
                    <span class="unit">{{ formatAmountTextBySize(Math.abs(item.profitLossAmount)) }}</span>
                  </div>
                  <div class="content-item-title">盈亏金额</div>
                </div>
              </template>
              <div class="content-item net-value">
                <div class="content-item-value">
                  <span>{{ item.transactionNetValue }}</span>
                </div>
                <div class="content-item-title">成交净值</div>
              </div>
            </div>
          </template>
        </van-cell>
      </van-cell-group>
      <van-pagination
        v-if="transactionLogTotal > customerParams.rows"
        v-model="customerParams.page"
        :total-items="transactionLogTotal"
        :items-per-page="customerParams.rows"
        :show-page-size="5"
        force-ellipses
        @change="getTransactionLogList"
      />
    </div>

    <EditCustomer ref="EditCustomerRef" />
    <Trade ref="TradeRef" userType="user" @refresh="onTradeSuccess" />
  </van-popup>
</template>

<script setup>
import { ref } from 'vue'
import { apiUpdateCustomerState, apiGetCustomerTransactionLogList, apiGetCustomerDetail } from '@/api/customer'
import EditCustomer from './edit.vue'
import Trade from '../product/trade.vue'
import { showToast } from 'vant'
import dayjs from 'dayjs'
import { formatAmountBySize, formatAmountTextBySize } from '@/utils/common'

const emit = defineEmits(['refresh'])

const showPopup = ref(false)
const form = ref({})
const EditCustomerRef = ref()
const TradeRef = ref()
const transactionLogList = ref([])
const transactionLogTotal = ref(0)

const customerParams = ref({
  page: 1,
  rows: 10,
  userId: ''
})

const open = async (customer) => {
  getCustomerDetail(customer)
  customerParams.value.userId = customer.id
  getTransactionLogList()
  showPopup.value = true
}

const editCustomer = () => {
  EditCustomerRef.value.open(form.value, 'edit')
}

const getCustomerDetail = async (customer) => {
  apiGetCustomerDetail({ id: customer.id }).then(res => {
    res.symbol = !res.profitLoss ? '' : res.profitLoss > 0 ? '+' : '-'
    form.value = res
  }).catch(() => {
    form.value = customer
  })
}

const deleteCustomer = async () => {
  if (form.value.assets || form.value.cost || form.value.holdingUnits) {
    showToast({
      message: '客户有持仓，不能删除',
      position: 'top'
    })
    return
  }
  apiUpdateCustomerState({ id: form.value.id, state: 0 }).then((res) => {
    showToast({
      message: '删除成功',
      position: 'top'
    })
    setTimeout(() => {
      showPopup.value = false
      emit('refresh')
    }, 1000)
  })
}

const getTransactionLogList = async (page = 1) => {
  customerParams.value.page = page
  apiGetCustomerTransactionLogList(customerParams.value).then((res) => {
    res.list.forEach((item) => {
      item.symbol = !item.profitLossAmount ? '' : item.profitLossAmount > 0 ? '+' : '-'
    })
    transactionLogList.value = res.list
    transactionLogTotal.value = res.total
  })
}

const startTrade = (tradeType) => {
  TradeRef.value.open(form.value, tradeType)
}

const onTradeSuccess = async () => {
  getCustomerDetail(form.value)
  getTransactionLogList()
}

const close = () => {
  showPopup.value = false
  emit('refresh')
}

defineExpose({
  open
})
</script>

<style lang="less" scoped>
.detail-wrapper {
  padding-top: var(--van-nav-bar-height);
  height: calc(100vh - var(--van-nav-bar-height));
  background-color: #f7f7f7;
  overflow-y: auto;
  .btn-wrapper {
    padding: 16px;
    display: flex;
    justify-content: space-between;
    .btn-item {
      width: 47%;
    }
  }
  .title {
    font-size: 16px;
    font-weight: bold;
  }
  .bold {
    font-weight: bold;
  }
  .trade-wrapper {
    display: flex;
    align-items: center;
    color: #323232;
    .trade-info {
      flex: 1;
      margin: 0 10px;
      .trade-info-item {
        display: flex;
        align-items: center;
        font-size: 12px;
        .trade-info-label {
          min-width: 5em;
        }
      }
    }
    .content-item {
      text-align: center;
      height: 100%;
      &.net-value {
        min-width: 55px;
      }
      &.income-loss {
        min-width: 100px;
      }

      .content-item-title {
        margin-top: 10px;
      }

      .content-item-value {
        display: flex;
        align-items: baseline;
        justify-content: center;
        font-size: 22px;
        height: 22px;
        line-height: 22px;
        font-weight: bold;

        .unit {
          font-size: 12px;
          margin-left: 2px;
        }

        &.loss {
          color: #43c07d;
        }

        &.income {
          color: #f53f3f;
        }
      }
    }
  }
}
</style>
